using AutoMapper;
using UwinEducation.Application.Common.Interfaces;
using UwinEducation.Application.Dtos;
using UwinEducation.Application.Extensions;
using UwinEducation.Domain.Entities;
using UwinEducation.Domain.IRepositories;
using UwinEducation.Shared.Models;

namespace UwinEducation.Application.Services
{
    /// <summary>
    /// 学生服务实现
    /// </summary>
    public class StudentService : IStudentService
    {
        private readonly IStudentRepository _studentRepository;
        private readonly IAppointmentRepository _appointmentRepository;
        private readonly IOrderRepository _orderRepository;
        private readonly IOrderDetailRepository _orderDetailRepository;
        private readonly IMapper _mapper;

        public StudentService(
            IStudentRepository studentRepository,
            IAppointmentRepository appointmentRepository,
            IOrderRepository orderRepository,
            IOrderDetailRepository orderDetailRepository,
            IMapper mapper
        )
        {
            _studentRepository = studentRepository;
            _appointmentRepository = appointmentRepository;
            _orderRepository = orderRepository;
            _orderDetailRepository = orderDetailRepository;
            _mapper = mapper;
        }

        /// <summary>
        /// 获取学生分页列表
        /// </summary>
        public async Task<PagedResult<StudentDto>> GetPagedListAsync(StudentPageRequest pageRequest)
        {
            var result = await _studentRepository.GetPagedListAsync(pageRequest);
            var studentDtos = _mapper.Map<List<StudentDto>>(result.Items);

            // 获取所有学生的预约数量
            var studentIds = result.Items.Select(s => s.Id).ToList();
            var appointments = await _appointmentRepository.GetByStudentIdsAsync(studentIds);
            var appointmentCounts = appointments
                .GroupBy(a => a.StudentId)
                .ToDictionary(g => g.Key, g => g.Count());

            // 设置每个学生的预约数量
            foreach (var studentDto in studentDtos)
            {
                studentDto.AppointmentCount = appointmentCounts.GetValueOrDefault(studentDto.Id);
            }

            return new PagedResult<StudentDto>
            {
                Total = result.Total,
                Items = studentDtos
            };
        }

        /// <summary>
        /// 获取学生详情
        /// </summary>
        public async Task<StudentDto> GetByIdAsync(Guid id)
        {
            var student = await _studentRepository.GetDetailsByIdAsync(id);
            if (student == null)
            {
                throw new ArgumentException($"学生不存在: {id}");
            }
            
            return _mapper.Map<StudentDto>(student);
        }

        /// <summary>
        /// 创建学生
        /// </summary>
        public async Task<StudentDto> CreateAsync(CreateStudentDto input)
        {
            // 检查学号是否已存在
            if (await _studentRepository.ExistsByStudentNoAsync(input.StudentNo))
            {
                throw new ArgumentException($"学号已存在: {input.StudentNo}");
            }

            var student = Student.Create(
                input.StudentNo,
                input.Name,
                input.School ?? string.Empty,
                input.Grade.GetEnrollmentDate(),
                input.Remarks ?? string.Empty,
                input.Phone ?? string.Empty,
                input.Email ?? string.Empty
            );

            await _studentRepository.AddAsync(student);
            return _mapper.Map<StudentDto>(student);
        }

        /// <summary>
        /// 更新学生
        /// </summary>
        public async Task<StudentDto> UpdateAsync(UpdateStudentDto input)
        {
            var student = await _studentRepository.GetByIdAsync(input.Id);
            if (student == null)
            {
                throw new ArgumentException($"学生不存在: {input.Id}");
            }

            student.Name = input.Name;
            student.School = input.School;
            student.EnrollmentDate = input.Grade.GetEnrollmentDate();
            student.Phone = input.Phone ?? student.Phone;
            student.Email = input.Email ?? student.Email;
            student.Remarks = input.Remarks ?? student.Remarks;

            await _studentRepository.UpdateAsync(student);
            return _mapper.Map<StudentDto>(student);
        }

        /// <summary>
        /// 删除学生
        /// </summary>
        public async Task DeleteAsync(Guid id)
        {
            var student = await _studentRepository.GetByIdAsync(id);
            if (student == null)
            {
                throw new ArgumentException($"学生不存在: {id}");
            }
            // // 检查订单详情是否存在
            // var orderDetails = await _orderDetailRepository.GetByStudentIdAsync(id);
            // if (orderDetails.Any())
            // {
            //    throw new ArgumentException($"学生: {student.Name} 存在订单课程列表，不能删除");
            // }
            //检查订单是否存在
            var orders = await _orderRepository.GetByStudentIdAsync(id);
            if (orders.Any())
            {
                throw new ArgumentException($"学生: {student.Name} 存在订单，不能删除");
            }


            await _studentRepository.DeleteAsync(id);
        }

        /// <summary>
        /// 根据学生IDs获取学生列表
        /// </summary>
        public async Task<List<StudentDto>> GetListByIdsAsync(List<IdRequest> request)
        {
            var students = await _studentRepository.GetListByIdsAsync(request);
            return _mapper.Map<List<StudentDto>>(students);
        }

        /// <summary>
        /// 获取学生编号最大值
        /// </summary>
        public async Task<int> GetMaxStudentNoAsync()
        {
            return await _studentRepository.GetMaxStudentNoAsync();
        }
    }
}